/**
  普通话等级考试-新增考试
*/
<template>
  <div class="operate-exam-container">
    <div style="height: 30px;">
      <el-breadcrumb style="float: left;" separator="/">
        <el-breadcrumb-item :to="{ path: '/putonghuaExamsCreate' }">
        <span @click="reback()">{{ $t('mandarin.createExams') }}</span></el-breadcrumb-item>
        <el-breadcrumb-item v-if="operateMode === 'add'">{{ $t('common.btn.add') }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="operateMode === 'edit'">{{ $t('common.btn.edit') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button style="float:right; padding:0;" type="text" @click="reback()">{{ $t('common.btn.back') }}</el-button>
    </div>
    <el-card style="padding: 0!important;" shadow="never" v-loading="loading" body-style="padding: 24px;">
      <div slot="header">
        <div class="title" v-if="operateMode === 'add'">{{ $t('mandarin.addExam') }}</div>
        <div class="title" v-if="operateMode === 'edit'">{{ $t('mandarin.editExam') }}</div>
      </div>
      <el-form :model="examForm" label-position="right" class="exam-form" ref="examForm" label-width="110px">
        <el-row>
          <el-col :span="16">
            <el-form-item
              :label="$t('mandarin.contestTitle') + ':'"
              prop="title"
              :rules="[{ required: true, message: $t('mandarin.requireContestTitle'), trigger: 'blur' }, { validator: checkSpecial, trigger: 'blur'}]">
              <el-input :placeholder="$t('common.pla.pleaseInput')" v-model="examForm.title" :maxlength="60" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('subjectCompetitionBase.semester') + ':'" prop="calendarId"
              :rules="[{ required: true, message: $t('subjectCompetitionBase.requireSemester'), trigger: 'change'}]">
              <CalendarSelect v-model="examForm.calendarId"></CalendarSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('mandarin.registrationStartTime') + ':'"
              prop="signUpStart"
              :rules="[{ required: true, message: $t('mandarin.requireRegisStartTime'), trigger: 'change'}]">
              <el-date-picker
                v-model="examForm.signUpStart"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :placeholder="$t('common.pla.pleaseSelect')"
                :picker-options="bmkssjPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="$t('mandarin.registrationEndTime') + ':'"
              prop="signUpEnd"
              :rules="[{ required: true, message: $t('mandarin.requireRegistEndTime'), trigger: 'change'}]">
              <el-date-picker
                v-model="examForm.signUpEnd"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :placeholder="$t('common.pla.pleaseSelect')"
                :picker-options="bmjssjPickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="8">
            <el-form-item
              :label="$t('mandarin.listSet') + ':'"
              prop="listSet"
              :rules="[{ required: true, message: $t('mandarin.requireListSet'), trigger: 'change'}, { validator: checkListSet, trigger: 'change'}]">
              <el-button style="line-height: 10px;" type="text" size="medium" @click="listSetting()">{{ $t('mandarin.listSet') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="24">
            <el-form-item
              :label="$t('mandarin.examExplanation') + ':'"
              prop="remark"
              :rules="[{ required: true, message: $t('mandarin.requireExamExplanation'), trigger: 'blur'},{ validator: checkSpecial, trigger: 'change'}]">
              <Tinymce style="margin: 20px;" ref="editor" :height="200" :simple="false" :hideMenu="true" v-model="examForm.remark" :toolbar="toolbar"/>
            </el-form-item>
            <!-- <span>{{examForm.listSet.length}}</span>
            <span>{{ $t('mandarin.limitExamExplanation') + examForm.listSet + $t('mandarin.char') }} </span> -->
          </el-col>
        </el-row>
      </el-form>
      <div class="operate-btn-container">
        <div class="float-right">
          <el-button @click="cancelOperate()">{{ $t('common.btn.cancel') }}</el-button>
          <el-button type="primary" @click="confirmOperate()">{{ $t('common.btn.confirm') }}</el-button>
        </div>
      </div>
    </el-card>
    <el-dialog
      :before-close="beforeClose"
      :title="$t('mandarin.listSet')"
      width="70%"
      class="examination-dialog"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <list-setting ref="addListSet" v-if="operateMode === 'add'" :addConfirmData="addConfirmData" @close-list-setting="closeListSetting" @confirm-list-setting="confirmAddListSetting"></list-setting>
      <edit-list-setting ref="editListSet" v-if="operateMode === 'edit'"
        :editConfirmData="editConfirmData"
        @close-list-setting="closeListSetting"
        @confirm-list-setting="confirmEditListSetting"
        @delete-list-setting="deleteListSetting">
      </edit-list-setting>
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from 'common/src/components/tinymce';
import listSetting from './listSetting';
import editListSetting from './editListSetting';
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
export default {
  components: {
    Tinymce,
    'list-setting': listSetting,
    'edit-list-setting': editListSetting
  },
  data() {
    return {
      examForm: {
        title: '',
        calendarId: '',
        signUpStart: '',
        signUpEnd: '',
        listSet: '',
        remark: ''
      },
      toolbar:['undo redo | styleselect | fontselect | formatselect | fontsizeselect | forecolor backcolor | bold italic underline strikethrough | table | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist |  fullscreen '],
      dialogVisible: false,
      addConfirmData: [],
      editConfirmData: [],
      deleteIdList: []
    }
  },
  props: {
    operateMode: {
      type: String,
      default: ''
    },
    operateData: {
      type: Object,
      default: () => {}
    },
    rows: {
      type: Object,
      default: () => {}
    },
  },
  computed: {
    bmkssjPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.examForm.signUpEnd) {
            // 报名开始时间必须小于报名截止时间
            if (value.getTime() > new Date(_this.examForm.signUpEnd.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    },
    bmjssjPickerOptions() {
      let _this = this
      return {
        disabledDate: (value) => {
          if (_this.examForm.signUpStart) {
            // 评分截止时间必须大于评分开始时间
            if (value.getTime() + (24 * 60 * 60 * 1000) < new Date(_this.examForm.signUpStart.split(' ')[0]).getTime()) {
              return true
            }
          }
          return false
        }
      }
    }
  },
  created() {

  },
  methods: {
    // 校验特殊字符$
    checkSpecial(rule, value, callback) {
      let regEn = /[`$]/im;
      if (regEn.test(value)) {
        callback(new Error(this.$t('subjectCompetitionBase.specialText')))
      } else {
        callback()
      }
    },
    // 校验名单
    checkListSet(rule, value, callback) {
      if (!value || (value.length && value.length === 0)) {
        callback(new Error(this.$t('mandarin.requireListSet')))
      } else {
        callback()
      }
    },
    reback() {
      this.$emit('change-exam-create-index')
    },
    // 名单设置
    listSetting() {
      this.dialogVisible = true
    },
    // 取消操作
    cancelOperate() {
      this.$emit('change-exam-create-index')
    },
    deleteListSetting(val) {
      this.deleteIdList = val
    },
    // 确认操作
   async confirmOperate() {
      this.$refs['examForm'].validate( async valid => {
        if (valid) {

          if(this.operateMode === 'edit'){
              let endTime = new Date(this.rows.signUpEnd.replace('-', '/')).getTime()
              let nowTimeResponse = await graduateStudentApi.getCurrentSystemTime()
              if (nowTimeResponse.data) {
                nowTimeResponse.data = new Date(nowTimeResponse.data).getTime()
              }
              if (!(nowTimeResponse.data <= endTime)) {
                this.$eduConfirm(this.$t('mandarin.registEndTime') + '（' + this.rows.signUpEnd + '）已过').then(_ => {})
                return
              }
          }

          if (this.examForm.signUpStart > this.examForm.signUpEnd) {
            this.$eduAlert(this.$t('mandarin.validateRegistTime'), this.$t('graduateBase.prompt'), {
              type: 'warning'
            })
            return
          }
          if (this.operateMode === 'add') {
            subjectCompetitionApi.addPutonghuaExamNew({
              "examCompetition": {
                "title": this.examForm.title,
                "signUpStartStr": this.examForm.signUpStart,
                "signUpEndStr": this.examForm.signUpEnd,
                "calendarId": this.examForm.calendarId,
                "remark": this.examForm.remark,
                "examCategory": 2,
                "educationTag": 1
              },
              "examSignUpListList": this.examForm.listSet
            }).then(res => {
              if (res.code === 200) {
                this.$emit('change-exam-create-index')
              }
            })
          } else {
            subjectCompetitionApi.modifyPutonghuaExamNew({
              "examCompetition": {
                "id": this.examForm.id,
                "title": this.examForm.title,
                "signUpStartStr": this.examForm.signUpStart,
                "signUpEndStr": this.examForm.signUpEnd,
                "calendarId": this.examForm.calendarId,
                "remark": this.examForm.remark,
                "examCategory": 2,
                "educationTag": 1
              },
              "examSignUpListList": this.examForm.listSet,
              "deleteIdList": this.deleteIdList
            }).then(res => {
              if (res.code === 200) {
                this.$emit('change-exam-create-index')
              }
            })
          }
        }
      })
    },
    // 新增-关闭按钮-关闭弹框
    beforeClose() {
      this.dialogVisible = false
      if (this.operateMode === 'add') {
        this.$refs['addListSet'].cancelOperate()
        this.$refs['addListSet'].clearSereset()
      } else {
        this.$refs['editListSet'].cancelOperate()
        this.$refs['editListSet'].clearSereset()
      }
    },
    // 新增-取消按钮-关闭弹框
    closeListSetting() {
      this.dialogVisible = false
      // if (this.operateMode === 'add') {
      //   // this.$refs['addListSet'].cancelOperate()
      //   this.$refs['addListSet'].clearSereset()
      // } else {
      //   // this.$refs['editListSet'].cancelOperate()
      //   this.$refs['editListSet'].clearSereset()
      // }
    },
    // 新增-确认按钮-确认名单
    confirmAddListSetting(val) {
      this.addConfirmData = val
      this.examForm.listSet = val.map(value => {
        return {
          studentId: value.studentId,
          studentName: value.name,
          sex: value.sex,
          sexI18n: value.sexI18n,
          college: value.faculty,
          collegeI18n: value.facultyI18n,
          atSchoolStatus: value.leaveSchool,
          atSchoolStatusI18n: value.leaveSchoolI18n,
          studentStatus: value.registrationStatus,
          studentStatusI18n: value.registrationStatusI18n,
          enrolMethods: value.enrolMethods,
          enrolMethodsI18n: value.enrolMethodsI18n,
          campus: value.campus,
          campusI18n: value.campusI18n
        }
      })
      this.dialogVisible = false
      this.$refs.examForm.validateField('listSet')
    },
    // 编辑-确认按钮-确认名单
    confirmEditListSetting(val) {
      this.editConfirmData = val
      this.examForm.listSet = val.map(value => {
        return {
          id: value.id,
          studentId: value.studentId,
          studentName: value.name,
          sex: value.sex,
          sexI18n: value.sexI18n,
          college: value.faculty,
          collegeI18n: value.facultyI18n,
          atSchoolStatus: value.leaveSchool,
          atSchoolStatusI18n: value.leaveSchoolI18n,
          studentStatus: value.registrationStatus,
          studentStatusI18n: value.registrationStatusI18n,
          enrolMethods: value.enrolMethods,
          enrolMethodsI18n: value.enrolMethodsI18n
        }
      })
      this.dialogVisible = false
      this.$refs.examForm.validateField('listSet')
    }
  },
  watch: {
    "operateData": {
      handler(newVal) {
        if (this.operateMode === 'edit' || this.operateMode === 'details') {
          this.examForm = JSON.parse(JSON.stringify(newVal))
          this.editConfirmData = this.examForm.listSet
        }
      },
      deep: true,
      immediate: true
    },
    "examForm.remark.length": {
      handler(newVal) {
        if (newVal && this.$refs.examForm) {
          this.$refs.examForm.validateField('examExplanation')
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy() {
    this.$refs['examForm'].resetFields()
  }
}
</script>
<style lang="scss" scoped>
  .operate-exam-container ::v-deep {
    .el-breadcrumb__item:last-child ::v-deep {
      .el-breadcrumb__inner {
        color: #606266;
        font-weight: bold;
        cursor: default
      }
    }
    .el-breadcrumb__item ::v-deep {
      .is-link {
        color: #aaa;
        font-weight: unset;
      }
      .is-link:hover {
        color: #409eff;
      }
    }
    .exam-form {
      padding-right: 10px;
    }
    .exam-form ::v-deep {
      .el-date-editor.el-input {
        width: 100%!important;
      }
      .editor-custom-btn-container {
        display: none;
      }
      .tinymce-container {
        margin: 0!important;
      }
    }
    .title {
      font-size: 18px;
    }
    .el-divider--horizontal {
      margin: 10px 0 20px 0 !important;
    }
    .operate-btn-container {
      border-top: 1px solid #ebeef5;
      padding: 20px;
      margin-bottom: 30px;
    }
  }

</style>
